import { deleteTreeHole, queryHoleList } from "@/api/content/treeHole";
import { useState, useCallback, useEffect } from "react";
import { Treehole } from "../../../../types/content/treeHole";
import { message } from "antd";

export const useWhisperTable = () => {
    const [messageApi] = message.useMessage();
    const [loading, setLoading] = useState(false);
    const [searchForm, setSearchForm] = useState<Treehole.Query>({
        keyword: ''
    });
    const [pagination, setPagination] = useState<Pagination>({
        pageNo: 1,
        pageSize: 10,
        total: 0,
    });
    const [tableData, setTableData] = useState<Treehole.Row[]>([]);
    /**
     * 获取标签列表
     */
    const getHoleList = useCallback(async () => {
        setLoading(true);
        const params = {
            pageNo: pagination.pageNo,
            pageSize: pagination.pageSize,
            keyword: searchForm.keyword || '',
        };
        const res = await queryHoleList(params);
        setLoading(false);
        if (res.code === 200) {
            setTableData(res.data.rows || []);
            setPagination({
                pageNo: pagination.pageNo,
                pageSize: pagination.pageSize,
                total: res.data.total,
            });
        }
    }, [pagination.pageNo, pagination.pageSize, searchForm]);


    /**
  * 删除
  * @param id 
  */
    const removeTreeHole = async (row: Treehole.Row) => {
        const res = await deleteTreeHole({
            ids: [row.id]
        })
        if (res.code === 200) {
            messageApi.success('删除成功!')
            getHoleList()
            if (tableData.length === 1) {
                setPagination({
                    pageNo: Math.max(1, pagination.pageNo - 1),
                    pageSize: pagination.pageSize,
                    total: pagination.total
                })
            } else {
                getHoleList()
            }
        }
    }
    useEffect(() => {
        getHoleList();
    }, [getHoleList, searchForm]);
    return {
        tableData,
        pagination,
        loading,
        removeTreeHole,
        setPagination,
        setSearchForm
    }
}